import {
  $wuxToast
} from '../../dist/index'
import config_data from '../../utils/config';
import constants from '../../constant/constants';
import md5Util from '../../utils/md5';
import { $wuxToptips } from '../../dist/index'

var _post_json = require("../../utils/network.js")._post_json;

Page({
  data: {
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    userName: "",
    passWord: "",
    loginBtndIsabled: true

  },
  checkLoginBtnIsabled: function(userName, pwd) {
    if (userName != "" && pwd.length >= 6) {
      this.data.loginBtndIsabled = false;
      this.setData({
        loginBtndIsabled: false
      });
    } else {
      this.setData({
        loginBtndIsabled: true
      });
    }
  },
  listenerUserNameInput: function(e) {
    this.data.userName = e.detail.value;
    this.checkLoginBtnIsabled(this.data.userName, this.data.passWord);
  },

  listenerPassWordInput: function(e) {
    this.data.passWord = e.detail.value;
    this.checkLoginBtnIsabled(this.data.userName, this.data.passWord);
  },

  onLoad: function() {

  },
  bindGetUserInfo: function(e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮
      var that = this;

      wx.login({
        success: res => {
          if (res.code) {
            const code = res.code;
            wx.getUserInfo({
              withCredentials: true,
              success: res => {
                // 可以将 res 发送给后台解码出 unionId
                const oauthData = res.userInfo
                this.setData({
                  spinning: true,
                })
                _post_json("user/login4MiniApp", {
                  "code": code,
                  "rawData": res.rawData,
                  "signature": res.signature,
                  "encryptedData": res.encryptedData,
                  "iv": res.iv,
                  "userName": this.data.userName,
                  "password": md5Util.hexMD5(this.data.passWord)
                }).then((res) => {
                  console.log("openId" + res.data.data.openId)
                  
                  //登录成功.设置全局变量OpenId 设置本地缓存
                  wx.setStorage({
                    key: "openId",
                    data: res.data.data.openId
                  })

                  //记得设置userInfo全局变量. 不然index页面获取不到头像和昵称
                  getApp().globalData.userInfo = oauthData;
                  //设置登录成功标记 isLoginSuccess
                  wx.setStorageSync('isLoginSuccess', constants.yesFlagNum);
                  //关闭loading
                  this.setData({
                    spinning: false,
                  })
                  wx.redirectTo({
                    url: '../index/index'
                  })

                }, (res) => {
                  this.setData({
                    spinning: false,
                  })
                  let respCode = res.data.respCode;
                  if (respCode == 401 || respCode == 400){
                    $wuxToptips().error({
                      hidden: false,
                      text: "用户名或密码错误!",
                      duration: 3000,
                      success() { },
                    })
                  }else{
                    $wuxToptips().error({
                      hidden: false,
                      text: "登录失败,原因未知(请联系管理员 错误代码 : " + respCode+")!",
                      duration: 3000,
                      success() { },
                    })
                  }
                });
              }
            })
          } else {
            $wuxToast().show({
              type: 'forbidden',
              duration: 1500,
              color: '#fff',
              text: '从微信服务器登录失败 , 可能网络超时!',
              success: () => console.log('禁止操作')
            })
          }
        }
      })

    } else {
      //用户按了拒绝按钮
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击了“返回授权”')
          }
        }
      })
    }
  }
})